package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"goods/models"
)

type GoodsController struct {
	beego.Controller
}
type JsonRes struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (g *GoodsController) Add() {
	name := g.GetString("name")
	price, _ := g.GetFloat("price", 64)
	num, _ := g.GetInt("num")
	startTime := g.GetString("startTime")
	intro := g.GetString("intro")
	goods := models.Goods{
		Name:      name,
		Price:     price,
		Num:       num,
		StartTime: startTime,
		Intro:     intro,
	}
	err := models.CreateGoods(&goods)
	if err != nil {
		data := JsonRes{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		g.Data["json"] = data
		g.ServeJSON()
	} else {
		data := JsonRes{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		g.Data["json"] = data
		g.ServeJSON()
	}
}
func (g *GoodsController) List() {
	var goods []models.Goods
	err := models.GoodsLIst(goods)
	if err != nil {
		data := JsonRes{
			Code: 500,
			Msg:  "查询失败",
			Data: nil,
		}
		g.Data["json"] = data
		g.ServeJSON()
	} else {
		data := JsonRes{
			Code: 200,
			Msg:  "查询成功",
			Data: goods,
		}
		g.Data["json"] = data
		g.ServeJSON()
	}
}
func (g *GoodsController) Del() {
	id, _ := g.GetInt("id")
	err := models.Del(id)
	if err != nil {
		data := JsonRes{
			Code: 500,
			Msg:  "删除失败",
			Data: nil,
		}
		g.Data["json"] = data
		g.ServeJSON()
	} else {
		data := JsonRes{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		g.Data["json"] = data
		g.ServeJSON()
	}
}
